from flask import Flask, url_for
from flask import Flask, Response
from flask_restful import Api, Resource, reqparse
from flask_cors import *  # 导入模块
from pre_process import explore
from clustering import Clustring
from id3 import ID3
from ml_compare import train

app = Flask(__name__)
api = Api(app)


class HelloWorld(Resource):
    def get(self):
        return {"message": "Hello, world!"}


class Preprocess(Resource):
    def get(self):
        img_name = explore.main()
        return "pre_process/" + img_name
    

class Clustering(Resource):
    def get(self):
        img_kmeans = Clustring.Kmeans_plot()
        img_dbscan = Clustring.DBScan_plot()
        return ["clustering/"+img_kmeans, "clustering/"+img_dbscan]
    
class Id3(Resource):
    def __init__(self) -> None:
        super().__init__()
        # flask restful 参数获取
        self.parser = reqparse.RequestParser()
        self.parser.add_argument('feature', type=str, location="args")
        # id3 分类树初始化
        dataSet, labels = ID3.createDataSet()
        self.featLabels = []
        self.tree = ID3.createTree(dataSet, labels, self.featLabels)

    def get(self):
        data = self.parser.parse_args()
        testVec = [int(x.strip()) for x in data.get('feature').split(",")]
        print(self.tree)
        print(self.featLabels)
        print(testVec)
        result = ID3.classify(self.tree, self.featLabels, testVec)
        print(result)
        return "predict: {}, label: {}".format(result, "non-exist" if result == 0 else "exist")


class MLCompare(Resource):
    def get(self):
        return ["ml_compare/" + x for x in train.train()]

class DownloadImage(Resource):
    def get(self, module, name):
        with open("{}/{}".format(module, name), "rb") as f:
            image = f.read()
        return Response(image, mimetype='image/jpeg')


api.add_resource(HelloWorld, "/")
api.add_resource(Preprocess, "/pre_process")
api.add_resource(Clustering, "/clustering")
api.add_resource(Id3, "/id3")
api.add_resource(MLCompare, "/ml_compare")
api.add_resource(DownloadImage, "/<string:module>/<string:name>")

if __name__ == "__main__":
    app.run(debug=True, port=8080)    
    CORS(app, resources={r"/*": {"origins": "*"}})
